package com.pengli.mytools.greendao;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;

import com.pengli.mytools.MyApplication;

import org.greenrobot.greendao.database.Database;

/**
 * 数据库连接控制器
 */
public class GreenDaoDBController {

//    static DatabaseContext databaseContext = new DatabaseContext(MyApplication.getInstance());
    private static final String DBNAME = "mytools.sqLiteDatabase";

    private static DaoMaster.DevOpenHelper helper;
    private static SQLiteDatabase sqLiteDatabase;
    private static DaoMaster daoMaster;
    private static DaoSession daoSession;
    private static Database database;


    public static void initGreenDao() {
        helper = new DaoMaster.DevOpenHelper(MyApplication.getInstance(), DBNAME);
        sqLiteDatabase = helper.getWritableDatabase();
        daoMaster = new DaoMaster(sqLiteDatabase);
        daoSession = daoMaster.newSession();
        database = daoSession.getDatabase();
    }

    //数据库重置
    public static void reSetTables() {
        DaoMaster.dropAllTables(daoMaster.getDatabase(), true);
        DaoMaster.createAllTables(daoMaster.getDatabase(), true);
    }

    public static void excuteSql(String sql){
        database.execSQL(sql);
    }

    public static Database getDatabase() {
        return database;
    }

    public static DaoMaster.DevOpenHelper getHelper() {
        return helper;
    }

    public static SQLiteDatabase getSqLiteDatabase() {
        return sqLiteDatabase;
    }

    public static DaoMaster getDaoMaster() {
        return daoMaster;
    }

    public static DaoSession getDaoSession() {
        return daoSession;
    }

    //获取apk的db存储路径
    public static String getAppInfo() {

        // 获取packageManager的实例
        PackageManager packageManager = MyApplication.getInstance().getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        try {
            PackageInfo packInfo = packageManager.getPackageInfo(MyApplication.getInstance().getPackageName(), 0);
            return packInfo.applicationInfo.dataDir;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
}
